$NG.AllReady(function (page, { useAction, useAttachmentReturn, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const config = {
        asrid: '',
        u_lxzt_init: ''
    }
    const user = $NG.getUser()
    const mstform = $NG.getCmpApi("p_form_kjxmgl__m")

    if (page.isList) {
        // 创建选框
        tranceLevelWindow()
        const toolbar = $NG.getCmpApi("toolbar")
        const drid = $NG.getCmpApi("grid")
        toolbar.insert({
            id: "updateProjectStatus",
            text: "更新立项状态",
            iconCls: "icon-New"
        });

        useClick(() => {
            const selectRows = drid.getSelectedData()
            if (selectRows.length !== 1) {
                $NG.alert("请选中一条单据！")
                return
            }
            const row = selectRows[0]
            if (row.u_zd) {
                $NG.alert("当前单据立项状态已修改，不能重复修改！")
                return
            }
            window.traceLeveOpenModal()
        }, "updateProjectStatus")
    }

    window.traceLeveConfirmModal = (value) => {
        const toolbar = $NG.getCmpApi("toolbar")
        const drid = $NG.getCmpApi("grid")
        const selectRows = drid.getSelectedData()
        if (selectRows.length !== 1) {
            $NG.alert("请选中一条单据！")
            return
        }
        const row = selectRows[0]
        $NG.execServer("UPDATE", { tableName: "p_form_kjxmgl__m", valueSql: `u_lxzt = '${value}' , u_zd='GG爆'`, filterSql: `phid = '${row.phid}'` }, (res) => {
            if (res.status == 'success') {
                $NG.alert("调整成功！")
                $NG.refresh()
            } else {
                $NG.alert("调整失败！")

            }
            window.traceLeveCloseModal()
        })
    }


    if (page.oType == 'add') {

        const u_lxzt = mstform.getItem("u_lxzt").getValue()
        u_lxzt || mstform.getItem("u_lxzt").setValue('03')
        const year = new Date().getFullYear()
        $NG.updateState((updater) => {
            updater.data.p_form_kjxmgl__m.setProps({
                u_tbnd: {
                    label: year,
                    value: year
                },
                u_sm: `包括:1.科技项目申报书;2.科技项目预算书;3.科技查新报告:4.知识产权分析报告:5.二级单位立项文件.`
            })
        })
    }
    if (page.oType == 'add' || page.oType == 'edit') {
        selectUlxzt()
        mstform.getItem("u_bz1").setValue('“立项时间”和”立项状态”两项由总局科技人员填写!')
    }

    useBeforeClick(async () => {
        const result = await tableAttachInit()
        if (!result) {
            return false
        }
        const num = result.data.attachmentRecordList.length
        if (num == 0) {
            $NG.alert("您还没有上传附件，请上传附件！")
            return false
        }
        return true
    }, 'save')

    // 监听单据附件弹窗返回
    useAttachmentReturn(({ args }) => {
        // 附件弹框点击的确认还是取消
        console.log('status', args[0].closeStatus);
        // 附件的asrSessionGuid
        config.asrid = args[0].asrSessionGuid
        console.log("asrid", args[0].asrSessionGuid);
    });

    useValuesChange(() => {
        getProjectInfoByPhid()
    }, "p_form_kjxmgl__m.u_ytxfmc")

    // 立项状态
    useValuesChange(() => {
        selectUlxzt()
    }, "p_form_kjxmgl__m.u_lxzt")

    function selectUlxzt() {
        const u_lxzt = mstform.getItem("u_lxzt").getValue()
        if (u_lxzt && u_lxzt != '03') {
            $NG.updateUI((updater) => {
                updater.fieldSetForm.p_form_kjxmgl__m.u_lxzt.setProps({
                    disabled: true
                })
            })
        }
        config.u_lxzt_init = u_lxzt
    }

    function getProjectInfoByPhid() {
        const phid = mstform.getItem("u_ytxfmc").getValue()
        if (!phid) return
        $NG.execServer("getProjectInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_kjxmgl__m.setProps({
                    bill_name: datas.bill_name,
                    ng_insert_dt: datas.start_date,
                    u_xmjsrq: datas.end_date
                })
            })
        })
    }

    // 查询附件，找到附件的数量
    async function tableAttachInit() {
        if (!config.asrid) {
            $NG.alert("请上传附件")
            return false
        }
        const origin = location.origin
        const router = "/JFileSrv/reactAttach/tableAttachInit"
        const param = {
            asrSessionGuid: config.asrid,
            busTypeCode: "Disclose_First",
            asrFill: user.userID,
            asrFillName: user.userName,
            asrTable: 'FirstLevelDisclosureFrom',
            asrCode: page.oType == 'add' ? config.asrid : mstform.getValues().phid,
            orgId: user.orgID,
            colAttach: '0',
            uCode: '0001'
        }
        const query = new URLSearchParams(param).toString();
        const url = `${origin}${router}?${query}`;
        try {
            const res = await fetch(url, {
                method: 'GET',
                headers: {
                    "dbToken": '0001'
                }
            });
            if (!res.ok) {
                throw new Error(`HTTP 错误：${res.status}`);
            }
            // 假设接口返回 JSON
            const data = await res.json();
            console.log("返回数据：", data);
            // 根据业务逻辑处理
            if (data.code == 200) {
                return data
            } else {
                console.warn("请求返回异常：", data.message || data);
                $NG.alert("获取附件数量发生异常，请联系管理员！")
                return false
            }
        } catch (err) {
            console.error("请求失败：", err);
            $NG.alert("获取附件数量发生异常，请联系管理员！")
            return false
        }

    }
})


// 创建跟踪界别弹框
// %这里window.traceLeveConfirmModal需要重写(value)=>void;打开window.traceLeveOpenModal()，关闭window.traceLeveCloseModal()
function tranceLevelWindow() {
    const css = `body{font-family:"Microsoft YaHei",Arial,sans-serif;background:#f5f5f5}.gzjb_modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.4);display:flex;justify-content:center;align-items:center;opacity:0;pointer-events:none;transition:opacity 0.3s ease;z-index:999}.gzjb_modal-overlay.gzjb_show{opacity:1;pointer-events:auto}.gzjb_modal{background:#fff;border-radius:12px;width:320px;padding:25px 20px;box-shadow:0 10px 25px rgba(0,0,0,0.2);transform:translateY(-20px);transition:transform 0.3s ease,opacity 0.3s ease;opacity:0}.gzjb_modal-overlay.gzjb_show .gzjb_modal{transform:translateY(0);opacity:1}.gzjb_modal h2{margin-top:0;color:#1890ff;font-size:20px;text-align:center}.gzjb_modal select{width:100%;padding:10px;margin:20px 0;border:1px solid #d9d9d9;border-radius:6px;appearance:none;outline:none;font-size:14px;transition:border-color 0.3s}.gzjb_modal select:focus{border-color:#1890ff;box-shadow:0 0 0 2px rgba(24,144,255,0.2)}.gzjb_modal-buttons{display:flex;justify-content:flex-end;gap:10px}.gzjb_modal-buttons button{padding:8px 16px;border:none;border-radius:6px;cursor:pointer;font-size:14px;transition:background 0.3s}.gzjb_confirm-btn{background-color:#1890ff;color:#fff}.gzjb_confirm-btn:hover{background-color:#40a9ff}.gzjb_cancel-btn{background-color:#f0f0f0;color:#333}.gzjb_cancel-btn:hover{background-color:#d9d9d9}`
    const html = `<div class="gzjb_modal-overlay" id="gzjb_modalOverlay"><div class="gzjb_modal"><h2>跟踪设置</h2><label for="gzjb_trackingLevel">立项状态（修改一次）:</label><select id="gzjb_trackingLevel"><option value="01">集团立项</option><option value="02">公司立项</option><option value="03">未立项</option></select><div class="gzjb_modal-buttons"><button class="gzjb_cancel-btn">取消</button><button class="gzjb_confirm-btn">确定</button></div></div></div>`
    const body = document.querySelector("body")
    const styleTag = document.createElement('style');
    styleTag.appendChild(document.createTextNode(css));
    document.head.appendChild(styleTag);
    body.insertAdjacentHTML('afterbegin', html)
    const gzjb_modalOverlay = document.getElementById('gzjb_modalOverlay'), ok = document.querySelector(".gzjb_confirm-btn"), no = document.querySelector(".gzjb_cancel-btn"); ok.addEventListener('click', () => { gzjb_confirmModal() }), no.addEventListener('click', () => { if (window.traceLeveNoModal) { window.traceLeveNoModal(level) } }); function traceLeveOpenModal() { gzjb_modalOverlay.classList.add('gzjb_show') } function traceLeveCloseModal() { gzjb_modalOverlay.classList.remove('gzjb_show') } window.traceLeveOpenModal = traceLeveOpenModal, window.traceLeveCloseModal = traceLeveCloseModal; function gzjb_confirmModal() { const level = document.getElementById('gzjb_trackingLevel').value; if (!window.traceLeveConfirmModal) { $NG.alert("window.traceLeveConfirmModal 未重写，运行失败！请联系管理员！"); return } window.traceLeveConfirmModal(level), traceLeveCloseModal() } gzjb_modalOverlay.addEventListener('click', e => { e.target === gzjb_modalOverlay && traceLeveCloseModal() });
}
